﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.PointStore.Business;
using Top.Web.Api.Filters;
using Top.Business.OAuth;
using Top.Core;
using DuiBa;
using DuiBa.Models;
//using Top.PointStore.Filters;

namespace Top.PointStore.Controllers
{
    public class LoginController : ApiBase
    {
        private static string cacheIndex = string.Empty;
        private static string IndexHtml = string.Empty;
        private static string providerHtml = string.Empty;
        private static string redPacketsHtml = string.Empty;

        static LoginController()
        {
            cacheIndex = Top.Common.TopConfigHelper.GetAppSettings("CacheIndex");
            if (string.IsNullOrWhiteSpace(cacheIndex))
            {
                cacheIndex = "kaokao";
            }
            IndexHtml = ReadIndexHtml("~/index.html");
            redPacketsHtml = ReadIndexHtml("~/award.html");
        }



        /// <summary>
        /// 经纪人账号或者CRM账号登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="cityName"></param>
        /// <param name="userToken"></param>
        /// <param name="accesstoken"></param>
        /// <returns></returns>
        [NoLogin]
        [NoIdempotent]
        public async Task<object> Login(string name = "", string password = "", string cityName = "", Guid userToken = default(Guid), Guid accesstoken = default(Guid),string dbredirect="")
        {
            if (User != null)
            {
                if (Get("type", "") == "point")
                {
                    return Redirect(string.Format("/credit_detail.html?uk={0}&ver={1}", User.UserToken.ToString(), cacheIndex));
                }
                OAuthUser oauthUser = User;
                if (accesstoken != default(Guid))
                {
                    oauthUser = OAuthHelper.GetUserByAk(accesstoken.ToString());
                }
                T_PointMain_new t = await PointManager.GetV2(oauthUser);
                int vip=0;
                if(oauthUser.IsBroker)
                {
                    var broker=await BrokerManager.Get(oauthUser.BrokerID);
                    if (broker.F_StarStatus == 1)
                        vip = 1;
                    if (broker.F_Phone == "15967173754")
                        vip = 39;
                }
                var rel = DuiBaSDK.GenerateURL(new GenerateURLRequest() { uid = t.F_UserToken, credits = t.F_PointBalance, vip=vip,dbredirect=dbredirect });
                return Redirect(rel, false);

                //var result = HTML(IndexHtml);
                //return result.GetResponseMessage(this);
            }
            try
            {
                OAuthUser oauthUser = User;
                if (accesstoken != default(Guid) && oauthUser == null)
                {
                    oauthUser = OAuthHelper.GetUserByAk(accesstoken.ToString());
                }
                if (userToken != default(Guid) && oauthUser == null)
                {
                    oauthUser = OAuthHelper.GetUser(userToken.ToString());
                }
                if (oauthUser == null)
                {
                    //oauthUser =await LoginManager.Login(name, password);
                }
                if (oauthUser == null)
                {
                    return Redirect("/remind.html");
                }
                User = oauthUser;

                if (Configs.AppSettings.Get("BigTurnTableModel").ToLower() != "open")
                {
                    GlobalResourceManager.CheckBrokerOrAdimIsExist(User);
                    GlobalResourceManager.CheckUserTokenIsExist(User);
                    GlobalResourceManager.CheckPointMainIsExist(User);
                }

                if (Get("type", "") == "point")
                {
                    return Redirect(string.Format("/credit_detail.html?uk={0}&ver={1}", User.UserToken.ToString(), cacheIndex));
                }

                T_PointMain_new t = await PointManager.GetV2(User);
                int vip = 0;
                if (User.IsBroker)
                {
                    var broker = await BrokerManager.Get(oauthUser.BrokerID);
                    if (broker.F_StarStatus == 1)
                        vip = 1;
                }
                var rel = DuiBaSDK.GenerateURL(new GenerateURLRequest() { uid = t.F_UserToken, credits = t.F_PointBalance, vip=vip });
                return Redirect(rel, false);

                //var result = HTML(IndexHtml);
                //return result.GetResponseMessage(this);
            }
            catch (Exception ex)
            {
                return Redirect("/warning.html");
            }
        }

        [NoLogin]
        public object GetUser()
        {
            return User;
        }


        public static string ReadIndexHtml(string filePath)
        {
            string result = string.Empty;
            string url = HttpContext.Current.Server.MapPath(filePath);//"~/index.html"
            using (StreamReader sr = new StreamReader(url))
            {
                result = sr.ReadToEnd();
            }
            return result;
        }


        public async Task<bool> GetIsDistribute()
        {
            bool isDistribute = false;
            if (User.IsBroker && User.BrokerID != 0)
            {
                isDistribute = await LoginManager.IsInDistribute(User);
            }
            return isDistribute;
        }

        public object Logout()
        {
            User = null;
            return 1;
        }


    }
}
